package org.haredot.media;

import org.haredot.exception.DaoAccessException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MediaType {

    private final String type ;

    private final Charset charset ;

    public static final String APPLICATION_X_WWW_FORM_URLENCODED_STRING = "application/x-www-form-urlencoded";

    public static final MediaType APPLICATION_X_WWW_FORM_URLENCODED = new MediaType(APPLICATION_X_WWW_FORM_URLENCODED_STRING);

    public static final String MULTIPART_FORM_DATA_STRING = "multipart/form-data";

    public static final MediaType MULTIPART_FORM_DATA = new MediaType(MULTIPART_FORM_DATA_STRING);

    public static final String APPLICATION_JSON_STRING = "application/json";

    public static final MediaType APPLICATION_JSON = new MediaType(APPLICATION_JSON_STRING);


    public MediaType(String type) {
        this(type, StandardCharsets.UTF_8);
    }

    public MediaType(String type, Charset charset) {
        this.type = type ;
        this.charset = charset ;
    }

    @Override
    public String toString() {
        return this.type + ";charset=" + charset.name();
    }

    public static MediaType of(String contentType) {
        String[] split = contentType.split(";charset=");

        if (split.length == 1) {
            String[] split1 = contentType.split(";");
            return new MediaType(split1[0]);
        }
        if (split.length == 2) {
            return new MediaType(split[0], Charset.forName(split[1]));
        }
        throw new DaoAccessException("ContentType类型对应的值" + contentType + "无法被 MediaType 解析");
    }

    public String getType() {
        return type;
    }

    public Charset getCharset() {
        return charset;
    }
}
